package com.lz.ub

import android.content.Context
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbManager
import com.lz.ub.assist.UBCAssistCallback
import com.lz.ub.assist.UBCAssistDispatcher

/**
 * @author You
 * 辅助设备管理, 只能被动连接, 只有发送功能和接收功能
 */
class UBCAssistManager private constructor(
    usbManager: UsbManager, baudRate: Int, dataB: Int, stopB: Int, parity: Int
) : UBCAssistCallback {

    companion object {
        //instance
        private var INSTANCE: UBCAssistManager? = null

        internal fun init(
            usbManager: UsbManager, baudRate: Int = UBC_BAUD_RATE,
            dataB: Int = UBC_DATA_BITS, stopB: Int = UBC_STOP_BITS, parity: Int = UBC_PARITY
        ) {
            if (INSTANCE == null) INSTANCE = UBCAssistManager(usbManager, baudRate, dataB, stopB, parity)
        }

        fun get(): UBCAssistManager {
            if (INSTANCE == null) throw IllegalStateException("You need init(context) first")
            return INSTANCE!!
        }
    }

    private val dispatcher = UBCAssistDispatcher(usbManager, baudRate, dataB, stopB, parity, this)

    //回调
    private val callbacks = ArrayList<UBCAssistCallback>()

    fun isOpened(): Boolean = dispatcher.isOpened()

    fun isAvailable(): Boolean = dispatcher.isAvailable()

    fun close() {
        dispatcher.close()
    }

    fun send(data: String): Boolean = dispatcher.send(data)

    fun addUBCAssistCallback(callback: UBCAssistCallback) {
        callbacks.add(callback)
    }

    fun removeUBCAssistCallback(callback: UBCAssistCallback) {
        callbacks.remove(callback)
    }

    //插入USB设备
    internal fun addUsbDevice(device: UsbDevice) {
        Logger.i(
            UBCManager.TAG,
            "******add assist usbDevice (name = ${device.deviceName}) dispatcher isOpened = ${dispatcher.isOpened()} ******"
        )
        if (!dispatcher.isOpened()) dispatcher.open(device)
    }

    //拔出USB设备
    internal fun removeUsbDevice(device: UsbDevice) {
        Logger.d(UBCManager.TAG, "******remove assist UsbDevice (name = ${device.deviceName}) *****")
        if (dispatcher.usbDeviceId == device.deviceId) dispatcher.close()
    }

    override fun onRead(data: String) {
        callbacks.forEach { it.onRead(data) }
    }

    override fun onConnected(mac: String) {
        callbacks.forEach { it.onConnected(mac) }
    }

    override fun onDisconnected(mac: String) {
        callbacks.forEach { it.onDisconnected(mac) }
    }
}